package devicedbgui;

import devicedbgui.data.TestCase;
import devicedbgui.data.Device;
import devicedbgui.data.TestResult;
import devicedbgui.data.TestResultDAO;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.KeyEvent;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileFilter;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableColumn;

/** Displays test result information */
public class TestResultPanel extends javax.swing.JPanel {
    /** Reference to GUI class for accessing its variables */
private GUI gui;
    Hashtable<Integer, TestResult> htTestResult = new Hashtable<Integer, TestResult>();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /** Constructor creates all components belonging to panel */   
    public TestResultPanel() {
        initComponents();
    }
    /** Displays error messages */  
public void showError(JFrame parent, String error)
    {
        JOptionPane.showMessageDialog(parent, error);
    }
    /** Adds row to Jtable */
    private void addRow(DefaultTableModel model, TestResult item)
    {
       model.addRow(new Object[]{item.idTestResult, item.getStatement(),
            item.getResultDetail(), sdf.format(item.time), item.TestCase_idTestCase, item.getTestCaseDetail(),
                    item.getTestCaseDescription(), item.exeDescription, item.deviceName, item.deviceSerial});
    }
/** Displays all test results for a device  */
    public void showAllTestResults(GUI gui, Device device)
    {
        this.gui = gui;
     
        TestResultDAO dd = new TestResultDAO(gui.connection);
        try {
            ArrayList<TestResult> testResults = dd.selectByDeviceEx(device.record);
            DefaultTableModel model = (DefaultTableModel)tblTestResult.getModel();
            model.getDataVector().clear();
            int index = 0;                                
            for (TestResult item : testResults){
                htTestResult.put(new Integer(index++), item);                
                //model.addRow(new Object[]{item.idTestResult, item.name, item.description, sdf.format(item.time), item.TestCase_idTestCase,
                  //  item.testCaseDescription, item.exeDescription, item.deviceName, item.deviceSerial});
                addRow(model, item);
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
    /** Displays test results for a test case  */
    public void showTestResults(GUI gui, TestCase testCase)
    {
        this.gui = gui;
      
        TestResultDAO dd = new TestResultDAO(gui.connection);
        try {
            ArrayList<TestResult> testResults = dd.selectByTestCaseEx(testCase.idTestCase);
            DefaultTableModel model = (DefaultTableModel)tblTestResult.getModel();
            model.getDataVector().clear();
            int index = 0;                                
            for (TestResult item : testResults){
                htTestResult.put(new Integer(index++), item);                
                //model.addRow(new Object[]{item.idTestResult, item.name, item.description, sdf.format(item.time), item.TestCase_idTestCase,
                    //item.testCaseDescription, item.exeDescription, item.deviceName, item.deviceSerial});
                addRow(model, item);
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
    /** Shows all test results */
    public void showAll(GUI gui)
    {
        this.gui = gui;
       // this.setTitle("All Test Results");
        TestResultDAO dd = new TestResultDAO(gui.connection);
        try {
            ArrayList<TestResult> testResults = dd.selectAllEx();
            DefaultTableModel model = (DefaultTableModel)tblTestResult.getModel();
            model.getDataVector().clear();
            int index = 0;                                
            for (TestResult item : testResults){
                htTestResult.put(new Integer(index++), item);                
                //model.addRow(new Object[]{item.idTestResult, item.name, item.description, sdf.format(item.time), item.TestCase_idTestCase,
                  //  item.testCaseDescription, item.exeDescription, item.deviceName, item.deviceSerial});
                addRow(model, item);
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
        this.setVisible(true);
    }
     /** Refreshes display of list of test cases in database */
    public void update()
    {
        TestResultDAO dd = new TestResultDAO(gui.connection);
        try {
            ArrayList<TestResult> records = null;
            if (!gui.getTestCaseID().equals(""))
                records = dd.selectByTestCaseEx(Integer.valueOf(gui.getTestCaseID()));
            else
                records = dd.selectAllEx();
            DefaultTableModel model = (DefaultTableModel)tblTestResult.getModel();
            model.getDataVector().clear();
            int index = 0;   
            htTestResult.clear();
            for (TestResult item : records){ 
                htTestResult.put(new Integer(index++), item);
                //model.addRow(new Object[]{item.idTestResult, item.name, item.description, sdf.format(item.time), item.TestCase_idTestCase,
                  //  item.testCaseDescription, item.exeDescription, item.deviceName, item.deviceSerial});
                addRow(model, item);
            }
        }
        catch (Exception ex){
            showError(gui.frame, ex.toString());
        }
       
    }
    /** Displays all information in Jtable */ 
    public void fillResult(ArrayList<TestResult> result)
    {       
        try {            
            DefaultTableModel model = (DefaultTableModel)tblTestResult.getModel();
            model.getDataVector().clear();
            int index = 0;
            htTestResult.clear();                    
            for (TestResult item : result){
                htTestResult.put(new Integer(index++), item);                
                //model.addRow(new Object[]{item.idTestResult, item.name, item.description, sdf.format(item.time), item.TestCase_idTestCase,
                  //  item.testCaseDescription, item.exeDescription, item.deviceName, item.deviceSerial});
                addRow(model, item);
            }
            
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        txtSearch = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        btnSave = new javax.swing.JButton();
        btnAdd = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnEdit = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblTestResult = new javax.swing.JTable(){public Component prepareRenderer(TableCellRenderer renderer,
            int rowIndex, int vColIndex) {
            Component c = super.prepareRenderer(renderer, rowIndex, vColIndex);
            if (rowIndex % 2 == 0 && !tblTestResult.isRowSelected(rowIndex)) {
                c.setBackground(new Color(237, 242, 251));
            }
            else if (tblTestResult.isRowSelected(rowIndex)){c.setBackground(new Color(184, 207, 229));}
            else { c.setBackground(getBackground());}
            return c;
        }
    }
    ;
    btnSearch = new javax.swing.JButton();
    jLabel3 = new javax.swing.JLabel();
    cbSearchCriteria = new javax.swing.JComboBox();
    jButton1 = new javax.swing.JButton();

    txtSearch.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            txtSearchbtnSearchActionPerformed(evt);
        }
    });

    jLabel2.setText("Search for:");

    btnSave.setText("Save");
    btnSave.setMnemonic(KeyEvent.VK_S);
    btnSave.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSaveActionPerformed(evt);
        }
    });

    btnAdd.setText("Add");
    btnAdd.setMnemonic(KeyEvent.VK_D);
    btnAdd.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnAddActionPerformed(evt);
        }
    });

    btnDelete.setMnemonic(KeyEvent.VK_DELETE);
    btnDelete.setText("Delete");
    btnDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnDeleteActionPerformed(evt);
        }
    });

    btnEdit.setMnemonic(KeyEvent.VK_I);
    btnEdit.setText("Edit");
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    tblTestResult.setModel(new javax.swing.table.DefaultTableModel(
        new Object [][] {
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null},
            {null, null, null, null, null, null}
        },
        new String [] {
            "Test Result ID", "Statement", "Statement Result", "Time", "Test Case ID", "Test Case"
        }
    ) {
        boolean[] canEdit = new boolean [] {
            false, false, false, false, false, false
        };

        public boolean isCellEditable(int rowIndex, int columnIndex) {
            return canEdit [columnIndex];
        }
    });
    tblTestResult.setGridColor(new java.awt.Color(204, 204, 255));
    tblTestResult.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
    TableColumn column=tblTestResult.getColumnModel().getColumn(1);
    column.setPreferredWidth(300);
    column=tblTestResult.getColumnModel().getColumn(5);
    column.setPreferredWidth(200);
    jScrollPane1.setViewportView(tblTestResult);

    btnSearch.setText("Search");
    btnSearch.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnSearchActionPerformed(evt);
        }
    });

    jLabel3.setText("in:");

    cbSearchCriteria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "TestResult ID", "TestCase ID" }));

    jButton1.setText("Clear");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            jButton1ActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
    this.setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jLabel2)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 276, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jLabel3)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(cbSearchCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, 101, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnSearch)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnSave)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnAdd)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnEdit)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(btnDelete)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
            .addComponent(jButton1)
            .addContainerGap(92, Short.MAX_VALUE))
        .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 943, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel2)
                .addComponent(txtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnSearch)
                .addComponent(jLabel3)
                .addComponent(cbSearchCriteria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(btnAdd)
                .addComponent(btnEdit)
                .addComponent(btnDelete)
                .addComponent(btnSave)
                .addComponent(jButton1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 236, Short.MAX_VALUE)
            .addContainerGap())
    );
    }// </editor-fold>//GEN-END:initComponents

private void txtSearchbtnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSearchbtnSearchActionPerformed
btnSearchActionPerformed(evt);
}//GEN-LAST:event_txtSearchbtnSearchActionPerformed
/** Saves test results to local computer */
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
JFileChooser fileChooser = new JFileChooser(".");
        fileChooser.setDialogTitle("Save Test Result");
        fileChooser.setDialogType(JFileChooser.OPEN_DIALOG);
        fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
        fileChooser.setFileFilter(new FileFilter() {

            public boolean accept(File f) {
                return f.getName().toLowerCase().endsWith(".csv") || f.isDirectory();
            }
            public String getDescription() {
                return "*.csv";
            }
        });
    if (fileChooser.showSaveDialog(this) == JFileChooser.APPROVE_OPTION){
       File file = fileChooser.getSelectedFile();
if (file.getName().indexOf('.')==-1){
    file = new File(file.getAbsolutePath()+".csv");
}  

        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));

             bw.write("TestResultID,Statement,StatementResult,Time,TestCaseID,TestCase\r\n");
            for (TestResult item : htTestResult.values()){
                bw.write(String.format("%d,%s,%s,%s,%d,%s\r\n", 

                        new Object[]{item.idTestResult, item.getStatement(),
                        item.getResultDetail(), item.time, item.TestCase_idTestCase,
                    item.getTestCaseDescription()}));
            }
            bw.flush();
            bw.close();
            JOptionPane.showMessageDialog(gui.frame, "File has been saved successfully");
        } catch (Exception e){
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
    }
}//GEN-LAST:event_btnSaveActionPerformed
/** add test result to database */
private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
//if (gui.connection == null)
        //return;
    EditTestResultDlg dlg = new EditTestResultDlg(gui, null, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        update();
    }
}//GEN-LAST:event_btnAddActionPerformed
/** Delete selected test result */
private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
int[] selected = tblTestResult.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    // ask user if he surely wants to delete this record
    int option = JOptionPane.showConfirmDialog(gui.frame, "Are you sure to delete selected record(s)?", "Confirmation", JOptionPane.YES_NO_OPTION);
    if (option == JOptionPane.YES_OPTION)
    {        
        TestResultDAO dd = new TestResultDAO(gui.connection);
        try {
            for (int i = 0; i < selected.length; i++){
                TestResult item = htTestResult.get(new Integer(selected[i]));   
                dd.delete(item.idTestResult);
                htTestResult.remove(new Integer(selected[i]));

            }           
            
        } catch (Exception e)
        {
            JOptionPane.showMessageDialog(gui.frame, e.toString());
        }
        update();
    }
}//GEN-LAST:event_btnDeleteActionPerformed
/** Edit test result */
private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEditActionPerformed
int[] selected = tblTestResult.getSelectedRows();  
    if (selected.length == 0){
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    TestResult item = htTestResult.get(new Integer(selected[0]));
    
    if (item == null)
    {
        JOptionPane.showMessageDialog(gui.frame, "No item has been selected, please select an item");
        return;
    }
    
    EditTestResultDlg dlg = new EditTestResultDlg(gui, item, true);
    dlg.setVisible(true);
    if (dlg.isModifiedDB){
        htTestResult.remove(new Integer(selected[0]));        
        htTestResult.put(new Integer(selected[0]), dlg.testResult);
        update();
    }
}//GEN-LAST:event_btnEditActionPerformed
/* Search button functionality */
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
if (gui.connection == null)
        return;
    String searchString = txtSearch.getText();
    // search criteria
    String criteria = this.cbSearchCriteria.getSelectedItem().toString();
    ArrayList<TestResult> searchResults = null;
    TestResultDAO dd = new TestResultDAO((gui.connection));
    try {
        if (criteria.equalsIgnoreCase("TestResult ID"))
            searchResults = dd.searchByID(Integer.parseInt(searchString));
        else if (criteria.equalsIgnoreCase("Statement"))
            searchResults = dd.searchByName(searchString);
        else if (criteria.equalsIgnoreCase("Result"))
            searchResults = dd.searchByDescription(searchString);
        else if (criteria.equalsIgnoreCase("TestCase ID"))
            searchResults = dd.searchByTestCaseID(Integer.parseInt(searchString));        
        
        // fill table
        fillResult(searchResults);
    } catch (Exception ex){
        JOptionPane.showMessageDialog(gui.frame, ex.toString());
    }
}//GEN-LAST:event_btnSearchActionPerformed

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
update();
}//GEN-LAST:event_jButton1ActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnEdit;
    private javax.swing.JButton btnSave;
    private javax.swing.JButton btnSearch;
    private javax.swing.JComboBox cbSearchCriteria;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tblTestResult;
    private javax.swing.JTextField txtSearch;
    // End of variables declaration//GEN-END:variables

}
